package com.chinasoft.controller;

import com.alibaba.fastjson.JSONArray;
import com.chinasoft.dao.Impl.SectionDAOImpl;
import com.chinasoft.dao.SectionDAO;
import com.chinasoft.entity.Section;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by YE on 2018/5/22.
 */
@WebServlet(name = "SectionServlet", urlPatterns = {"/section"})
public class SectionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SectionDAO sectionDAO = new SectionDAOImpl();
        Section section=null;
        PrintWriter out = response.getWriter();
        List<Section> list=null;
        String secop=request.getParameter("secop");
        if("getall".equals(secop)){
            list=sectionDAO.getAllSections();
            String sections=JSONArray.toJSONString(list);
            out.print(sections);
        }if("delete".equals(secop)){
            int sid=Integer.parseInt(request.getParameter("id"));
            out.print(sectionDAO.deleteSection(sid));
        }if("update".equals(secop)){
            section=new Section();
            section.setSid(Integer.parseInt(request.getParameter("sid")));
            section.setSname(request.getParameter("sname"));
            out.print(sectionDAO.updateSection(section));
        }if("insert".equals(secop)){
            section=new Section();
            section.setSname(request.getParameter("sname"));
            out.print(sectionDAO.addSection(section));
        }if("drop".equals(secop)) {
            int sid=Integer.parseInt(request.getParameter("sid"));
            section=sectionDAO.selectSection(sid);
            request.setAttribute("section", section);
            request.getRequestDispatcher("post.jsp").forward(request, response);
        }if("getallsec".equals(secop)){
            list=sectionDAO.getAllSections();
            request.setAttribute("list",list);
            request.getRequestDispatcher("forum.jsp").forward(request, response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
